package thread;

public class SyncDemo1 {
    static boolean success1 = false;
    static boolean success2 = false;

    public static void main(String[] args) throws InterruptedException {
        Bank bank = new Bank();
        int sum = 0;
        while (true) {
            sum++;
            new Thread(() -> {
                success1 = bank.getMoney(20000);
            }).start();
            new Thread(() -> {
                success2 = bank.getMoney(20000);
            }).start();

            Thread.sleep(10);
            if (success1 && success2) {
                System.out.println("第" + sum + "次成功");
                break;
            }else {
                success1 = false;
                success2 = false;
                bank.saveAccount(20000);
            }
        }
    }
}

class Bank {
    private int account = 20000;

    public synchronized boolean getMoney(int money) {
        int account = getAccount();
        if (account >= money) {
            account -= money;

            Thread.yield();

            saveAccount(account);
            return true;
        }
        return false;
    }

    public void saveAccount(int account) {
        this.account = account;
    }

    public int getAccount() {
        return account;
    }
}
